package com.shawn.baseappbygroovydsl.ui.views

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextUtils
import android.text.method.LinkMovementMethod
import android.text.style.BackgroundColorSpan
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.text.style.UnderlineSpan
import com.bumptech.glide.request.transition.Transition
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.target.CustomTarget
import com.choryan.quan.videowzproject.extension.ExtensionView.setGradientColor
import com.shawn.baseappbygroovydsl.R
import com.shawn.baseappbygroovydsl.base.AppBase
import com.shawn.baseappbygroovydsl.databinding.FragmentTextBinding
import com.shawn.baseappbygroovydsl.ui.adapter.AdapterViewFlipper
import com.shawn.baseappbygroovydsl.ui.base.FragmentBase
import com.shawn.baseappbygroovydsl.ui.extension.ExtensionCommon.toast
import com.shawn.baseappbygroovydsl.ui.extension.ExtensionLog.log
import com.shawn.baseappbygroovydsl.utils.ExtensionCommon.dp
import com.shawn.baseappbygroovydsl.utils.UtilCoin
import com.shawn.baseappbygroovydsl.utils.UtilHundredContribute
import com.yy.mobile.rollingtextview.CharOrder
import com.yy.mobile.rollingtextview.strategy.Strategy
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.random.Random

class TextFragment : FragmentBase<FragmentTextBinding>(R.layout.fragment_text) {
    private lateinit var slideshowViewModel: ViewModel

    private val animatorListener = AnimatorListener()

    inner class AnimatorListener : AnimatorListenerAdapter() {
        override fun onAnimationEnd(animation: Animator) {
            mHandler.postDelayed({
                mBind.rtv.setText("", false)
                startNumAnimation()
            }, 2000)
        }
    }

    override fun onKeyCodeBack(): Boolean {
        return false
    }
    override fun statusBar() {

    }

    override fun lazyLoad() {
        slideshowViewModel = ViewModelProvider(this)[NestedViewModel::class.java]
        initView()
    }

    override fun initClick() {

    }

    private fun initView() {
        effect1()
        effect2()
        effect3()
        effect4()
        goNextFrag()
        effectSsb()
        customTextType()
        rollingTextView()
        search()
        smearText()
        underText()
        gradientText()
    }

    private fun effect3() {
        startNumAnimation()
    }
    private fun startNumAnimation() {
        mBind.rtv.animationDuration = 1500L
        mBind.rtv.charStrategy = Strategy.CarryBitAnimation()
        mBind.rtv.addCharOrder(CharOrder.Number)
        mBind.rtv.animationInterpolator = AccelerateDecelerateInterpolator()
        mBind.rtv.removeAnimatorListener(animatorListener)
        mBind.rtv.addAnimatorListener(animatorListener)
        mBind.rtv.setText("33000", true)
    }

    private fun effect1() {
        mBind.vfUsrWithdrawInfo.adapter = AdapterViewFlipper(requireContext())
    }

    private fun effect2() {
        startLoopFriendContribute()
    }

    private fun effect4() {
        val ssb = SpannableStringBuilder()
        val str1 = "100级  金币加成(100%"
        val str2 = "+${30}%"
        val str3 = ")"
        ssb.append(str1).append(str2).append(str3)
        ssb.setSpan(
            ForegroundColorSpan(Color.parseColor("#E53B23")),
            str1.length,
            str1.length + str2.length,
            Spannable.SPAN_INCLUSIVE_EXCLUSIVE
        )
        mBind.tvSsb.text = ssb
    }

    private fun effectSsb() {
        val spannableStringBuilder = SpannableStringBuilder()
        val a = "《用户协议》"
        val and = "和"
        val b = "《隐私政策》"
        spannableStringBuilder.append(a).append(and).append(b)

        val aIndex = spannableStringBuilder.indexOf(a)
        val andIndex = spannableStringBuilder.indexOf(and)
        val bIndex = spannableStringBuilder.indexOf(b)

        val termsClickableSpan = object : ClickableSpan() {
            override fun onClick(widget: View) {
                "$a 点击".log()
            }
        }
        val userClickableSpan = object : ClickableSpan() {
            override fun onClick(widget: View) {
                "$b 点击".log()
            }
        }

        val aForegroundColorSpan = ForegroundColorSpan(AppBase.instance.resources.getColor(R.color.teal_200))
        val bForegroundColorSpan = ForegroundColorSpan(AppBase.instance.resources.getColor(R.color.teal_200))

        spannableStringBuilder.setSpan(
            aForegroundColorSpan, aIndex, aIndex + a.length,
            Spanned.SPAN_INCLUSIVE_INCLUSIVE
        )
        spannableStringBuilder.setSpan(
            termsClickableSpan, aIndex, aIndex + a.length,
            Spanned.SPAN_INCLUSIVE_INCLUSIVE
        )
        spannableStringBuilder.setSpan(
            userClickableSpan, bIndex, bIndex + b.length,
            Spanned.SPAN_INCLUSIVE_INCLUSIVE
        )
        spannableStringBuilder.setSpan(
            bForegroundColorSpan, bIndex, bIndex + b.length,
            Spanned.SPAN_INCLUSIVE_INCLUSIVE
        )
        mBind.tvSsb2.text = spannableStringBuilder
        mBind.tvSsb2.movementMethod = LinkMovementMethod.getInstance()
    }

    private fun customTextType() {
        val customFont = Typeface.createFromAsset(AppBase.instance.assets,"fonts/font_1.ttf")
        mBind.tvCustomTextType.typeface = customFont
    }

    private fun rollingTextView() {
        var a = 1.11
        mBind.btnRolling.setOnClickListener {
            val value = mBind.tvCoinTop.getText()
            if (value.isNotEmpty()) {
                mBind.tvCoinTop.animationDuration = 500L
                mBind.tvCoinTop.animationInterpolator = AccelerateDecelerateInterpolator()
            }
            a += Random.nextDouble(1.0, 2.0)
            mBind.tvCoinTop.setText(UtilCoin.getWithdrawActualAmountNew(a), true)
        }
    }

    private fun search() {
        val inputEdit = mBind.includeSearch.edInputSearch
        // 获取焦点拉起软键盘
        inputEdit.requestFocus()
        val imm = context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(inputEdit, InputMethodManager.SHOW_IMPLICIT)
        inputEdit.setOnEditorActionListener { _, actionId, _ ->
            when (actionId) {
                EditorInfo.IME_ACTION_DONE -> {
                    // 处理完成按钮的点击事件
                    // 例如，隐藏软键盘
                    true
                }
                EditorInfo.IME_ACTION_SEARCH -> {
                    // 处理搜索按钮的点击事件
                    // 执行搜索操作
                    "搜索按钮点击".toast()
                    hideSoftInput()
                    true
                }
                EditorInfo.IME_ACTION_SEND -> {
                    // 处理发送按钮的点击事件
                    // 发送数据
                    true
                }
                else -> false
            }
        }


        inputEdit.setOnClickListener {
            inputEdit.isCursorVisible = true
        }
    }

    private fun smearText() {
        val content = SpannableStringBuilder(mBind.tvSmear.text)
        content.setSpan(BackgroundColorSpan(Color.RED), 0, content.length / 2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
        mBind.tvSmear.text = content
    }

    private fun underText() {
        val content = SpannableStringBuilder(mBind.tvUnder.text)
        content.setSpan(UnderlineSpan(), 0, content.length / 2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
        mBind.tvUnder.text = content
    }

    private fun gradientText() {
        mBind.tvHello.setGradientColor(arrayOf("#000000", "#FF0000"))
    }

    private fun hideSoftInput() {
        val imm = context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view?.windowToken, 0)
    }

    private fun goNextFrag() {

    }

    override fun getData() {
        refreshHistory()
    }

    private fun loadUserIcon(view:View) {
        val tv = view as TextView
        tv.compoundDrawablePadding = 0.0f.dp.toInt()
        val size = 15f.dp.toInt()
        Glide.with(requireActivity()).load(UtilHundredContribute.curIcon()).override(size,size).transform(CircleCrop()).into(object :
            CustomTarget<Drawable>(){
            override fun onResourceReady(
                resource: Drawable,
                transition: Transition<in Drawable>?
            ) {
                tv.setCompoundDrawablesWithIntrinsicBounds(resource, null, null, null)
                tv.compoundDrawablePadding = 5.0f.dp.toInt()
            }

            override fun onLoadCleared(placeholder: Drawable?) {

            }
        })
    }

    private fun startLoopFriendContribute() {
        viewLifecycleOwner.lifecycleScope.launch {
            UtilHundredContribute.initPresentTxt(requireContext())
            mBind.tsLoopContribute.setFactory {
                val tv = TextView(requireContext())
                tv.setTextColor(Color.parseColor("#FFFFFFFF"))
                tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10f)
                tv.gravity = Gravity.CENTER
                tv.maxLines = 1
                tv.ellipsize = TextUtils.TruncateAt.END
                tv
            }
            mBind.tsLoopContribute.setCurrentText(UtilHundredContribute.curPresentTxt())
            loadUserIcon(mBind.tsLoopContribute.currentView)
            mBind.tsLoopContribute.setInAnimation(requireContext(), R.anim.translate_in)
            mBind.tsLoopContribute.setOutAnimation(requireContext(), R.anim.translate_out)
            repeat(Int.MAX_VALUE) {
                delay(1500L)
                mBind.tsLoopContribute.setText(UtilHundredContribute.curPresentTxt())
                loadUserIcon(mBind.tsLoopContribute.currentView)
            }
        }
    }

    override fun getBind(view: View): FragmentTextBinding {
        return FragmentTextBinding.bind(view)
    }

    private fun refreshHistory() {

    }

    companion object {
        const val type1 = "type"
        fun newInstance(): TextFragment {
            val args = Bundle()
            val fragment = TextFragment()
            fragment.arguments = args
            return fragment
        }
    }
}